<template>
	<view class="page-view" :style="skin">
		<zx-nav :title="(addrId ? '编辑' : '新增') + '地址'" bg="#fff" fixedTop></zx-nav>
		<view class="main">
			<view class="card mt20">
				<view class="group-row flex align-center u-border-bottom">
					<text class="title">收货人</text>
					<input placeholder="收货人姓名(至少两位)" name="input" v-model="info.contact_name" @input="inputVal" />
				</view>
				<view class="group-row flex align-center u-border-bottom">
					<text class="title">电话号码</text>
					<input placeholder="收货人电话号码" name="input" v-model="info.contact_phone" />
				</view>
				<!-- <view class="group-row flex align-center u-border-bottom">
					<text class="title">所在地区</text>
					<picker class="picker flex-sub" mode="region" @change="RegionChange" :value="region">
						<view class="picker" :style="{ color: region.length == 3 ? '#000' : '#8E8E93' }">{{ region.length == 3 ? regionName : '选择省市区' }}</view>
					</picker>
				</view>
				<view class="group-row flex align-center">
					<text class="title">详细地址</text>
					<input placeholder="详细街道地址" name="input" v-model="info.address" />
				</view> -->
				<view class="group-row flex align-center justify-between u-border-bottom" @tap="authVerification">
					<text class="title">所在地区</text>
					<view class="picker flex-sub" :style="{ color: region.length == 3 ? '#000' : '#878787' }">{{ region.length == 3 ? regionName : '选择省市区' }}</view>
					<u-icon name="map-fill" size="40" :color="themeColor"></u-icon>
				</view>
				<view class="group-row flex align-center justify-between " style="position: relative;">
					<text class="title">详细地址</text>
					<input class="flex-sub" placeholder="详细街道地址" name="input" v-model="info.address" />
					<tui-bubble-popup
						triangleTop="-22rpx"
						triangleLeft="145rpx"
						left="20rpx"
						direction="top"
						position="absolute"
						:top="110 + 'rpx'"
						:mask="false"
						:show="showTip"
						width="300rpx"
					>
						<view class="tui-chat-text u-p-20 text-center">记得完善详情信息</view>
					</tui-bubble-popup>
				</view>
			</view>

			<view class="defaultbox card flex justify-between  align-center mt20">
				<view class="">
					<view class="title">设置为默认地址</view>
					<view class="">每次下单时会使用默认地址</view>
				</view>
				<u-switch size="50" v-model="info.is_default" :activeValue="1" :inactiveValue="0" :activeColor="themeColor"></u-switch>
			</view>
		</view>
		<u-button @click="saveInfo" type="success" shape="circle" :loading="btnLoading" class="u-reset-button">保存</u-button>
		<!-- <simple-address ref="simpleAddress" :pickerValueDefault="cityPickerValueDefault" @onConfirm="onConfirm"></simple-address> -->
	</view>
</template>

<script>
import { mapMutations } from 'vuex';
// import simpleAddress from '@/components/simple-address/simple-address';
let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g;

/**
   * 格式化位置
   * @param {*} res chooseLocation成功后返回参数
   * 格式: {
  	 address: "山东省济南市槐荫区经十西路29851号"
     errMsg: "chooseLocation:ok"
     latitude: 36.65142
     longitude: 116.90084
     name: "济南市槐荫区人民政府"
     }
   */
const captureLocation = res => {
	// console.log('res', res);
	var regex = /^(北京市|天津市|重庆市|上海市|香港特别行政区|澳门特别行政区)/;
	var province = [];
	var addressBean = {
		province: null,
		country: null,
		city: null,
		address: null
	};
	function regexAddressBean(address, addressBean) {
		regex = /^(.*?[市]|.*?[州]|.*?地区|.*?特别行政区)(.*?[区]|.*?[市]|.*?[县])(.*?)$/g;
		var addxress = regex.exec(address);
		console.log('addxress', addxress);
		if (addxress) {
			addressBean.city = addxress[1];
			addressBean.country = addxress[2];
			addressBean.address = addxress[3] + '(' + res.name + ')';
		}
		// console.log(addxress);
	}
	if (!(province = regex.exec(res.address))) {
		regex = /^(.*?(省|自治区))(.*?)$/;
		province = regex.exec(res.address);
		addressBean.province = province[1];
		regexAddressBean(province[3], addressBean);
	} else {
		addressBean.province = province[1];
		regexAddressBean(res.address, addressBean);
	}
	return addressBean;
};
export default {
	data() {
		return {
			region: [],
			regionName: '',
			addrId: '',
			cityPickerValueDefault: [0, 0, 1],
			info: {
				contact_phone: '',
				contact_name: '',
				province: '',
				city: '',
				district: '',
				address: '',
				is_default: 0
			},
			btnLoading: false,
			showTip: false
		};
	},
	// components: { simpleAddress },
	onLoad(option) {
		if (option.id) {
			console.log('option.id', option.id);
			this.addrId = option.id;
			this.getAddrInfo();
		} else {
			this.addrId = '';
		}
	},
	created() {},
	methods: {
		...mapMutations(['SET_ADDRINFO']),
		inputVal(e) {
			let val = e.detail.value;
			if (val.match(reg)) {
				val = val.replace(reg, '');
				this.$nextTick(() => {
					this.info.contact_name = val;
				});
			}
		},
		getAddrInfo() {
			this.$postAction(this.$api.getAddrInfo + this.addrId).then(da => {
				if (da.code == 0) {
					let info = da.data;
					for (var key in this.info) {
						this.info[key] = info[key];
					}
					this.region = [this.info.province, this.info.city, this.info.district];
					this.regionName = this.region.join(' ');
				}
			});
		},
		RegionChange(e) {
			this.region = e.detail.value;
			this.info.province = this.region[0];
			this.info.city = this.region[1];
			this.info.district = this.region[2];
			this.regionName = this.region.join(' ');
		},
		openAddres() {
			this.$refs.simpleAddress.open();
		},
		onConfirm(e) {
			this.regionName = e.label;
			this.region = e.labelArr;
			this.info.province = this.region[0];
			this.info.city = this.region[1];
			this.info.district = this.region[2];
		},
		saveInfo() {
			let that = this;
			/* 保存地址信息 */
			for (var key in this.info) {
				console.log(this.info[key]);
				if (this.info[key] === '') {
					uni.showToast({
						title: '请完善地址信息',
						icon: 'none'
					});
					return false;
				}

				if (key == 'contact_name' && this.info[key].length < 2) {
					uni.showToast({
						title: '请填写至少两个字的收货人姓名',
						icon: 'none'
					});
					return false;
				}
				if (key == 'contact_phone' && !uni.$u.test.mobile(this.info[key])) {
					uni.showToast({
						title: '请填写正确的手机号码',
						icon: 'none'
					});
					return false;
				}
			}
			let param = Object.assign({}, this.info);
			if (that.addrId) {
				param.id = that.addrId;
			}
			var url = that.addrId ? this.$api.editAddr + this.addrId : this.$api.addAddr;
			this.$postAction(url, param).then(da => {
				if (da.code == 0) {
					uni.showToast({
						title: that.addrId ? '编辑地址成功' : '新增地址成功',
						icon: 'success'
					});
					this.SET_ADDRINFO(da.data);
					this.$Router.back();
				} else {
					uni.showToast({
						title: that.addrId ? '编辑地址失败' : '新增地址失败',
						icon: 'none'
					});
				}
			});
		},
		authVerification() {
			uni.getSetting({
				success: res => {
					if (res.authSetting['scope.userFuzzyLocation']) {
						/* 用户授权成功时走这里 */
						this.handerChooseLocation();
					} else if (res.authSetting['scope.userFuzzyLocation'] === undefined) {
						/* 用户未授权时走这里 */
						console.log('没有授权');
						this.handleOpenSetting();
					} else {
						/* 用户拒绝了授权后走这里 */
						console.log('拒绝了授权 false');
						this.handleOpenSetting();
					}
				}
			});
		},
		handerChooseLocation(latitude, longitude) {
			let latlng = uni.getStorageSync('latlng');
			uni.chooseLocation({
				latitude: latitude || latlng.latitude,
				longitude: longitude || latlng.longitude,
				success: async res => {
					console.log('wx.chooseLocation res=', res);
					// uni.setStorageSync('currentLocation', res);
					let locationObj = captureLocation(res);
					if (!locationObj.city) {
						let info = await this.getAddress(res.latitude, res.longitude);
						locationObj.city = info.city;
						locationObj.country = info.city;
						locationObj.address = res.address;
					}
					console.log('locationObj', locationObj);
					this.region = [locationObj.province, locationObj.city, locationObj.country];
					this.info.province = this.region[0];
					this.info.city = this.region[1];
					this.info.district = this.region[2];
					this.regionName = this.region.join(' ');
					this.info.address = locationObj.address;
					this.showTip = true;
					setTimeout(() => {
						this.showTip = false;
					}, 5000);
				},
				fail: function(err) {
					console.log('取消按钮', err);
				}
			});
		},
		handleOpenSetting() {
			wx.openSetting({
				success: res => {
					console.log('定位 openSetting', res);
					if (res.authSetting['scope.userFuzzyLocation']) {
						this.handerChooseLocation();
					}
				}
			});
		},
		getAddress(latitude, longitude) {
			return this.$postAction(this.$api.get_address, {
				location: longitude + ',' + latitude
			}).then(da => {
				if (da.code == 0) {
					return da.data;
				}
			});
		}
	}
};
</script>
<style lang="scss">
.page-view {
	font-size: 26upx;
	color: #1c1c1e;
	.group-row {
		margin: 0 22upx;
		padding: 30upx 10upx;

		.title {
			width: 160upx;
		}
		input {
			font-size: 26upx;
		}
		.picker {
			height: 1.4rem;
			line-height: 1.4rem;
		}
	}
	.defaultbox {
		font-size: 24upx;
		color: #8e8e93;
		line-height: 1.5;
		padding: 36upx 32upx;
		.title {
			font-size: 26upx;
			color: #1c1c1e;
		}
	}
	.u-button--normal {
		margin: 68upx 94upx 0;
		width: 562upx !important;
	}
}
</style>
